<template>
  <div class="page-container">
    <div class="header-section">
      <div class="title-container">
        <h2 class="page-title">智能植物识别</h2>
        <div class="title-decoration"></div>
      </div>
      <p class="subtitle">上传植物照片，发现大自然的奥秘</p>

      <el-upload
        class="upload-area"
        action="#"
        :http-request="uploadImage"
        :show-file-list="false"
        accept="image/*"
        drag
      >
        <div class="upload-trigger" :class="{ 'has-image': imageUrl }">
          <div class="upload-content">
            <el-icon class="upload-icon"><Upload /></el-icon>
            <div class="upload-text">
              <span class="primary-text">点击或拖拽图片上传</span>
              <span class="secondary-text">支持 JPG、PNG 格式图片</span>
            </div>
          </div>

          <div class="upload-features">
            <div class="feature-item">
              <el-icon><Picture /></el-icon>
              <span>快速识别</span>
            </div>
            <div class="feature-item">
              <el-icon><DataAnalysis /></el-icon>
              <span>准确度高</span>
            </div>
            <div class="feature-item">
              <el-icon><Connection /></el-icon>
              <span>智能分析</span>
            </div>
          </div>
        </div>
      </el-upload>
    </div>

    <transition name="fade">
      <div v-if="imageUrl || plantResults" class="content-container">
        <!-- 左侧图片预览区域 -->
        <div class="image-section">
          <div class="image-container" :class="{ loading: isLoading }">
            <img
              v-if="imageUrl"
              :src="imageUrl"
              class="preview-image"
              alt="植物图片"
            />
            <div class="image-overlay">
              <div class="overlay-content">
                <el-button
                  type="primary"
                  class="change-image-btn"
                  @click="triggerUpload"
                  :icon="Edit"
                >
                  更换图片
                </el-button>
              </div>
            </div>
            <div v-if="isLoading" class="loading-overlay">
              <el-progress
                type="circle"
                :percentage="loadingProgress"
                :status="loadingProgress === 100 ? 'success' : ''"
              />
            </div>
          </div>

          <div class="image-meta">
            <div class="meta-item">
              <el-icon><Calendar /></el-icon>
              <span>{{ currentDate }}</span>
            </div>
            <div class="meta-item">
              <el-icon><PictureFilled /></el-icon>
              <span>{{ imageSize }}</span>
            </div>
          </div>
        </div>

        <!-- 右侧识别结果区域 -->
        <div v-if="plantResults" class="result-section">
          <div class="result-header">
            <div class="header-main">
              <h3>识别结果</h3>
              <el-tag type="success" effect="dark" class="result-status">
                已完成分析
              </el-tag>
            </div>
            <div class="header-sub">
              <span class="result-count"
                >发现 {{ plantResults.length }} 个可能物种</span
              >
              <span class="analysis-time"
                >分析耗时 {{ analysisDuration }}s</span
              >
            </div>
          </div>

          <div class="results-container">
            <el-card
              v-for="(plant, index) in plantResults"
              :key="index"
              class="plant-card"
              :class="{ highlight: index === 0 }"
              shadow="hover"
            >
              <template #header>
                <div class="card-header">
                  <div class="header-left">
                    <div
                      class="rank-badge"
                      :class="{ 'top-rank': index === 0 }"
                    >
                      {{ index + 1 }}
                    </div>
                    <div class="name-container">
                      <span class="plant-name">{{ plant.name }}</span>
                      <span class="scientific-name">{{
                        getScientificName(plant)
                      }}</span>
                    </div>
                  </div>
                  <div class="header-right">
                    <el-progress
                      type="dashboard"
                      :percentage="Math.round(plant.score * 100)"
                      :color="getScoreColor(plant.score)"
                      :stroke-width="8"
                      :width="60"
                    >
                      <template #default="{ percentage }">
                        <span class="progress-label">
                          {{ percentage }}%
                          <span class="progress-text">可信度</span>
                        </span>
                      </template>
                    </el-progress>
                  </div>
                </div>
              </template>

              <div class="plant-info">
                <div v-if="plant.baike_info?.description" class="info-section">
                  <div class="section-title">
                    <el-icon><InfoFilled /></el-icon>
                    <span>植物简介</span>
                  </div>
                  <p class="description">{{ plant.baike_info.description }}</p>
                </div>

                <div
                  class="tags-section"
                  v-if="getFeatures(plant.baike_info?.description)"
                >
                  <div class="section-title">
                    <el-icon><Collection /></el-icon>
                    <span>特征标签</span>
                  </div>
                  <div class="tags-container">
                    <el-tag
                      v-for="feature in getFeatures(
                        plant.baike_info?.description
                      )"
                      :key="feature"
                      class="feature-tag"
                      effect="plain"
                      :color="getTagColor(feature)"
                    >
                      {{ feature }}
                    </el-tag>
                  </div>
                </div>

                <div class="actions-section">
                  <el-button
                    v-if="plant.baike_info?.baike_url"
                    type="primary"
                    class="action-button"
                    @click="openBaike(plant.baike_info.baike_url)"
                  >
                    <template #icon>
                      <el-icon><Link /></el-icon>
                    </template>
                    查看百科详情
                  </el-button>
                  <el-button
                    type="success"
                    class="action-button"
                    @click="shareResult(plant)"
                  >
                    <template #icon>
                      <el-icon><Share /></el-icon>
                    </template>
                    分享结果
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import {
  Upload,
  Picture,
  DataAnalysis,
  Connection,
  Edit,
  Calendar,
  PictureFilled,
  InfoFilled,
  Collection,
  Link,
  Share,
} from "@element-plus/icons-vue";
import axios from "axios";
import { ElMessage } from "element-plus";
// onUnmounted is not defined
import { onUnmounted } from "vue";

const plantResults = ref(null);
const imageUrl = ref(null);
const isLoading = ref(false);
const loadingProgress = ref(0);
const analysisDuration = ref(0);
const userAvatar = ref("@头像.png");

const currentDate = computed(() => {
  return new Date().toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });
});

const imageSize = ref("0 KB");

const uploadImage = async (options) => {
  try {
    const file = options.file;
    imageUrl.value = URL.createObjectURL(file);
    imageSize.value = formatFileSize(file.size);

    isLoading.value = true;
    loadingProgress.value = 0;

    // 模拟进度
    const progressInterval = setInterval(() => {
      if (loadingProgress.value < 90) {
        loadingProgress.value += Math.random() * 10;
      }
    }, 200);

    const startTime = Date.now();
    const formData = new FormData();
    formData.append("file", file);

    const response = await axios.post(
      "http://127.0.0.1:8088/api/plantDetect",
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }
    );

    clearInterval(progressInterval);
    loadingProgress.value = 100;

    analysisDuration.value = ((Date.now() - startTime) / 1000).toFixed(1);
    plantResults.value = response.data.data.allResults;

    ElMessage({
      type: "success",
      message: "识别成功",
      duration: 2000,
    });
  } catch (error) {
    console.error("Error:", error);
    ElMessage.error("识别失败：" + (error.response?.data || error.message));
  } finally {
    setTimeout(() => {
      isLoading.value = false;
    }, 500);
  }
};

const getScoreColor = (score) => {
  if (score >= 0.8) return "#67C23A";
  if (score >= 0.6) return "#E6A23C";
  return "#909399";
};

const getFeatures = (description) => {
  if (!description) return [];
  const keywords = description
    .split(/[,，。]/)
    .map((word) => word.trim())
    .filter((word) => word.length >= 2 && word.length <= 6)
    .slice(0, 4);
  return keywords;
};

const getTagColor = (feature) => {
  const colors = ["#e1f3d8", "#fdf6ec", "#ecf5ff", "#f5f7fa"];
  const hash = feature.split("").reduce((acc, char) => {
    return char.charCodeAt(0) + ((acc << 5) - acc);
  }, 0);
  return colors[Math.abs(hash) % colors.length];
};

const getScientificName = (plant) => {
  // 模拟获取学名，实际项目中应该从API获取
  return "Plantae sp.";
};

const formatFileSize = (bytes) => {
  if (bytes === 0) return "0 KB";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
};

const openBaike = (url) => {
  window.open(url, "_blank");
};

const shareResult = (plant) => {
  ElMessage({
    type: "success",
    message: `分享 ${plant.name} 的识别结果`,
    duration: 2000,
  });
};

const triggerUpload = () => {
  const uploadEl = document.querySelector(".upload-area .el-upload input");
  if (uploadEl) {
    uploadEl.click();
  }
};

onUnmounted(() => {
  if (imageUrl.value) {
    URL.revokeObjectURL(imageUrl.value);
  }
});
</script>

<style scoped>
.page-container {
  padding: 40px;
  max-width: 1440px;
  margin: 0 auto;
  background-color: #f8fafc;
  min-height: 100vh;
}

.header-section {
  text-align: center;
  margin-bottom: 48px;
}

.title-container {
  display: inline-block;
  position: relative;
  margin-bottom: 16px;
}

.page-title {
  font-size: 36px;
  color: #1a1a1a;
  margin: 0;
  font-weight: 600;
  background: linear-gradient(120deg, #34d399 0%, #3b82f6 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.title-decoration {
  position: absolute;
  bottom: -8px;
  left: 50%;
  transform: translateX(-50%);
  width: 60%;
  height: 4px;
  background: linear-gradient(90deg, #34d399 0%, #3b82f6 100%);
  border-radius: 2px;
}

.subtitle {
  color: #666;
  font-size: 18px;
  margin: 0 0 40px;
  font-weight: 300;
}

.upload-area {
  display: flex;
  justify-content: center;
}

.upload-trigger {
  width: 600px;
  min-height: 240px;
  border: 2px dashed #e2e8f0;
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
  padding: 32px;
  position: relative;
  overflow: hidden;
}

.upload-trigger:hover {
  border-color: #3b82f6;
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  margin-bottom: 32px;
}

.upload-icon {
  font-size: 48px;
  color: #3b82f6;
  transition: transform 0.3s;
}

.upload-trigger:hover .upload-icon {
  transform: scale(1.1);
}

.upload-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.primary-text {
  font-size: 18px;
  color: #1a1a1a;
  font-weight: 500;
}

.secondary-text {
  font-size: 14px;
  color: #666;
}

.upload-features {
  display: flex;
  gap: 32px;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px dashed #e2e8f0;
  width: 100%;
  justify-content: center;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
  padding: 8px 16px;
  background-color: #f8fafc;
  border-radius: 8px;
  transition: all 0.3s;
}

.feature-item:hover {
  background-color: #f0f9ff;
  color: #3b82f6;
}

.content-container {
  display: grid;
  grid-template-columns: minmax(320px, 420px) 1fr;
  gap: 40px;
  margin-top: 40px;
}

.image-section {
  position: sticky;
  top: 40px;
  height: fit-content;
}

.image-container {
  background-color: #fff;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  position: relative;
  transition: all 0.3s;
}

.image-container:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
}

.preview-image {
  width: 100%;
  height: auto;
  display: block;
  transition: transform 0.3s;
}

.image-container:hover .preview-image {
  transform: scale(1.02);
}

.image-overlay {
  position: absolute;
  inset: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
  opacity: 0;
  transition: all 0.3s;
  display: flex;
  align-items: flex-end;
  padding: 24px;
}

.image-container:hover .image-overlay {
  opacity: 1;
}

.overlay-content {
  width: 100%;
}

.change-image-btn {
  width: 100%;
  height: 40px;
  border-radius: 8px;
  font-weight: 500;
}

.loading-overlay {
  position: absolute;
  inset: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(4px);
}

.image-meta {
  display: flex;
  gap: 16px;
  margin-top: 16px;
  padding: 12px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  font-size: 13px;
}

.result-section {
  background-color: #fff;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
}

.result-header {
  margin-bottom: 32px;
}

.header-main {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.header-main h3 {
  margin: 0;
  font-size: 24px;
  color: #1a1a1a;
  font-weight: 600;
}

.result-status {
  font-size: 12px;
  padding: 0 12px;
  height: 24px;
  line-height: 24px;
}

.header-sub {
  display: flex;
  gap: 24px;
  color: #666;
  font-size: 14px;
}

.plant-card {
  margin-bottom: 24px;
  border-radius: 12px;
  transition: all 0.3s;
  border: 1px solid #e2e8f0;
}

.plant-card.highlight {
  border: 1px solid #3b82f6;
  background-color: #f0f9ff;
}

.plant-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.rank-badge {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #f1f5f9;
  color: #64748b;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 14px;
}

.rank-badge.top-rank {
  background: linear-gradient(120deg, #34d399 0%, #3b82f6 100%);
  color: white;
}

.name-container {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.plant-name {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
}

.scientific-name {
  font-size: 13px;
  color: #666;
  font-style: italic;
}

.progress-label {
  display: flex;
  flex-direction: column;
  align-items: center;
  line-height: 1;
}

.progress-text {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.plant-info {
  padding: 0 20px 20px;
}

.info-section {
  margin-bottom: 24px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #1a1a1a;
  font-weight: 500;
  margin-bottom: 12px;
}

.description {
  margin: 0;
  line-height: 1.8;
  color: #4b5563;
  font-size: 14px;
}

.tags-section {
  margin-bottom: 24px;
}

.tags-container {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.feature-tag {
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 13px;
}

.actions-section {
  display: flex;
  gap: 12px;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e2e8f0;
}

.action-button {
  flex: 1;
  height: 40px;
  border-radius: 8px;
  font-weight: 500;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

@media screen and (max-width: 1200px) {
  .content-container {
    grid-template-columns: 1fr;
  }

  .image-section {
    position: static;
  }

  .upload-trigger {
    width: 100%;
    max-width: 600px;
  }

  .page-container {
    padding: 20px;
  }

  .result-section {
    padding: 24px;
  }
}

@media screen and (max-width: 640px) {
  .upload-features {
    flex-direction: column;
    gap: 16px;
  }

  .feature-item {
    width: 100%;
    justify-content: center;
  }

  .actions-section {
    flex-direction: column;
  }

  .header-sub {
    flex-direction: column;
    gap: 8px;
  }
}

/* 高度调小*/
.result-section {
  background-color: #fff;
  border-radius: 16px;
  padding: 24px; /* Reduced from 32px */
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  max-height: 80vh; /* Added max height */
  overflow-y: auto; /* Added scrolling */
}

.result-header {
  margin-bottom: 24px; /* Reduced from 32px */
  position: relative; /* Make header sticky */
  top: 0;
  background: #fff;
  z-index: 1;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.plant-card {
  margin-bottom: 16px; /* Reduced from 24px */
  border-radius: 12px;
  transition: all 0.3s;
  border: 1px solid #e2e8f0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px; /* Reduced from 20px */
}

.plant-info {
  padding: 0 16px 16px; /* Reduced from 0 20px 20px */
}

.info-section {
  margin-bottom: 16px; /* Reduced from 24px */
}

.description {
  margin: 0;
  line-height: 1.6; /* Reduced from 1.8 */
  color: #4b5563;
  font-size: 14px;
}

.tags-section {
  margin-bottom: 16px; /* Reduced from 24px */
}

.actions-section {
  display: flex;
  gap: 12px;
  margin-top: 16px; /* Reduced from 24px */
  padding-top: 16px; /* Reduced from 24px */
  border-top: 1px solid #e2e8f0;
}

/* Add smooth scrolling to the result section */
.result-section {
  scrollbar-width: thin;
  scrollbar-color: #e2e8f0 transparent;
}

.result-section::-webkit-scrollbar {
  width: 6px;
}

.result-section::-webkit-scrollbar-track {
  background: transparent;
}

.result-section::-webkit-scrollbar-thumb {
  background-color: #e2e8f0;
  border-radius: 3px;
}
</style>